/**
 * 
 */
package com.moyq5.permit.center.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.moyq5.mvc.framework.jackson.result.StatusResult;

public class AbstractExceptionController {
	private static final Logger log = LoggerFactory.getLogger(AbstractExceptionController.class);
	
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor editor = new CustomDateEditor(df, true);// true表示允许为空，false反之
		binder.registerCustomEditor(Date.class, editor);
	}

	@ExceptionHandler({ MethodArgumentNotValidException.class })
	@ResponseBody
	public StatusResult handleBindException(MethodArgumentNotValidException ex) {
		StatusResult jsonResult = new StatusResult();
		BindingResult br = ex.getBindingResult();
		jsonResult.setCode(br.getFieldError().getCode());
		jsonResult.setMessage(br.getFieldError().getDefaultMessage());
		return jsonResult;
	}

	@ExceptionHandler({ BindException.class })
	@ResponseBody
	public StatusResult handleBindException(BindException ex) {
		StatusResult jsonResult = new StatusResult();
		BindingResult br = ex.getBindingResult();
		jsonResult.setCode(br.getFieldError().getCode());
		jsonResult.setMessage(br.getFieldError().getDefaultMessage());
		return jsonResult;
	}
	
	@ExceptionHandler({ Exception.class })
	@ResponseBody
	public StatusResult handleException(Exception ex) {
		log.error(ex.getMessage(), ex);
		StatusResult jsonResult = new StatusResult();
		jsonResult.setMessage(ex.getMessage());
		return jsonResult;
	}
	
	@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "no login")
	public ResponseEntity<String> handleUnAuthorized() {
	    return ResponseEntity.status(HttpStatus.FORBIDDEN).body("no login");
	}
	
}
